// utils/request.ts
export const baseUrl = 'http://106.53.100.223:8082' // 替换为你的后台地址

let isRefreshing = false
let refreshSubscribers = []

function onRefreshed(newToken) {
  refreshSubscribers.forEach(callback => callback(newToken))
  refreshSubscribers = []
}

function subscribeTokenRefresh(cb) {
  refreshSubscribers.push(cb)
}
function refreshTokenRequest() {
  const refreshToken = uni.getStorageSync('refreshToken')
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + '/user/refresh/token', // 替换为你实际的刷新接口
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'refreshToken': refreshToken
      },
      success: (res) => {
        if (res.data.code === 200) {
          const newToken = res.data.data.accessToken
          uni.setStorageSync('token', newToken)
          uni.setStorageSync('refreshToken', res.data.data.refreshToken)
          resolve(newToken)
        } else {
          reject(res)
        }
      },
      fail: reject
    })
  })
}

export function request(options) {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')

    const doRequest = () => {
      uni.request({
        url: baseUrl + options.url,
        method: options.method || 'GET',
        data: options.data || {},
        header: {
          'Content-Type': 'application/json',
          'Token': token ? `${token}` : '',
          ...(options.header || {}) // 支持传入额外 header
        },
        success: (res) => {
          if (res.data.code === 200) {
            resolve(res.data)
          } 
          else if (res.data.code === 401) {
            // token失效
            if (!isRefreshing) {
              isRefreshing = true
              refreshTokenRequest().then(newToken => {
                isRefreshing = false
                onRefreshed(newToken)
                request(options).then(resolve).catch(reject)
              }).catch(() => {
                isRefreshing = false
                uni.removeStorageSync('token')
                uni.removeStorageSync('refreshToken')
                uni.showToast({ title: '请重新登录', icon: 'none', duration: 3000 })
                reject(res)
              })
            } else {
              subscribeTokenRefresh((newToken) => {
                // 替换 token 后重新请求
                request(options).then(resolve).catch(reject)
              })
            }
            // Token 过期，可重定向到登录页
            // uni.showToast({ title: '请重新登录', icon: 'none' })
            // uni.getStorageSync('refreshToken')

            // uni.removeStorageSync('token')
            // uni.reLaunch({ url: '/pages/index/login' })
          } else if(res.data.code === 500){
            reject(res)
          } else {
            // uni.showToast({ title: res.message , icon: 'none' })
            // reject(res)
          }
        },
        fail: (err) => {
          // uni.showToast({ title: '网络错误', icon: 'none' })
          // reject(err)
        }
      })
    }
    doRequest(token)
  })
}

export function uploadFiles(options) {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')

    uni.uploadFile({
      url: baseUrl + options.url,
      filePath: options.filePath,
      name: options.name || 'file',
      formData: options.formData || {},
      header: {
        'Content-Type': 'multipart/form-data',
        'Token': token || '',
        ...(options.header || {})
      },
      success: (res) => {
        // 防止返回的是空字符串或非 JSON
        let data = res.data
        try {
          if (typeof data === 'string') {
            data = JSON.parse(data)
          }
        } catch (e) {
          console.error('上传接口返回非 JSON:', res.data)
          return reject(new Error('服务器响应异常'))
        }

        if (res.statusCode === 200 && data?.code === 200) {
          resolve(data)
        } else {
          console.error('上传失败:', data)
          uni.showToast({ title: data?.message || '上传失败', icon: 'none' })
          reject(data)
        }
      },
      fail: (err) => {
        uni.showToast({ title: '网络错误', icon: 'none', duration: 3000 })
        reject(err)
      }
    })
  })
}
